package com.example.demo.controller;


import com.example.demo.entity.UserEntity;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// @Controller + @ResponseBody; restful API
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    // http://localhost:8081/user/username + 请求方式(GET POST PUT DELETE)
    @GetMapping("/username")
    public String getUserName() {
        return "法外狂徒" + userService.getUserName();
    }

    /**
     * 1.增删改查
     *  - 1.1查: 查列表 查单个
     *      - controller 中定义接口地址和方法，
     *      - 方法中调用service层的接口方法（）
     */
     // GET http://localhost:8081/user/32
    @GetMapping(value = "/{id}")
    public UserEntity getUserById(@PathVariable int id) {
        return userService.getUserById(id);
    }

    @DeleteMapping(value = "/{id}")
    public int deleteUserById(@PathVariable int id) {
        return userService.deleteUserById(id);
    }

    //    http://localhost:8081/user/list
    @GetMapping(value = "/list")
    public List<UserEntity> list() {
        return userService.list();
    }

    //  新增用户
    // POST http://localhost:8081/user
    @PostMapping
    public UserEntity add(@RequestBody UserEntity user) {
        int id = userService.addUser(user);
        return userService.getUserById(id);
    }

    // 更新用户
    @PutMapping
    public UserEntity update(@RequestBody UserEntity user) {

        userService.updateUser(user);
        return userService.getUserById(user.getId());
    }
}
